const { logger } = require('../utils/logger');

function errorHandler(err, req, res, next) {
  logger.error({ err, path: req.path }, 'Unhandled error');

  if (res.headersSent) {
    return next(err);
  }

  const status = err.status || err.statusCode || 500;
  const response = {
    error: err.code || 'internal_error',
    message: err.message || 'Unexpected error'
  };

  if (err.details) {
    response.details = err.details;
  }

  res.status(status).json(response);
}

module.exports = { errorHandler };
